package com.hjsmallfly.syllabus.repository.user.local

import com.hjsmallfly.syllabus.bean.UserLogin
import com.hjsmallfly.syllabus.ext.EMPTY
import com.hjsmallfly.syllabus.ext.from_ui
import com.hjsmallfly.syllabus.repository.user.UserDataSource
import com.hjsmallfly.syllabus.room.record.UserToken
import com.tencent.mmkv.MMKV
import rx.Observable

class UserLocalDataSource : UserDataSource {

    private val kv = MMKV.defaultMMKV()

    override fun saveUserTokenByUserLogin(userLogin: UserLogin?) =
        saveUserToken(if (userLogin == null) null else UserToken(userLogin.username, userLogin.password))

    override fun saveUserToken(token: UserToken?): Observable<Boolean> {
        return Observable.create<Boolean> {
            if (token == null) {
                kv.remove(EXTRA_CURRENT_USER_TOKEN)
            } else {
                kv.encode(EXTRA_CURRENT_USER_TOKEN, token)
            }
            true
        }.from_ui()
    }

    override fun queryCurrentUserToken(): Observable<UserToken> {
        return Observable.create<UserToken> {
            it.onStart()
            val token = kv.decodeParcelable(EXTRA_CURRENT_USER_TOKEN, UserToken::class.java)
            if (token != null) {
                it.onNext(token)
                it.onCompleted()
            } else {
                it.onError(EMPTY)
            }
        }.from_ui()
    }

    companion object {
        private const val EXTRA_CURRENT_USER_TOKEN = "CurrentUserToken"
    }
}